import React, { useEffect } from 'react';
import { Button, Input, message, Row, Col } from 'antd';
import './index.less';

const { AMap } = window;
let map;
const Map = ({ value, onChange }) => {
  const marker = new AMap.Marker();
  const getLnglat = v => {
    const geoCoder = new AMap.Geocoder({
      city: '杭州',
    });
    geoCoder.getLocation(v, (status, result) => {
      if (status === 'complete' && result.geocodes.length) {
        const lnglat = result.geocodes[0].location;
        marker.setPosition(lnglat);
        map.add(marker);
        map.setFitView(marker);
      } else {
        message.error('根据地址查询位置失败');
      }
    });
  };

  const onload = () => {
    map = new AMap.Map('amap', {
      showIndoorMap: false,
      center: [120.222999823, 30.2548760575],
      layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
      zoom: 14,
      rotation: 45,
      viewMode: '3D',
      pitch: 0,
    });
    if (value.name) {
      getLnglat(value.name);
    }
    map.on('click', e => {
      const lnglat = e?.lnglat;
      const geocoder = new AMap.Geocoder({
        city: '杭州',
      });
      geocoder.getAddress([lnglat.lng, lnglat.lat], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          onChange({
            name: result?.regeocode?.formattedAddress?.slice(9),
            longitude: lnglat.lng,
            latitude: lnglat.lat,
          });
          marker.setPosition(lnglat);
          map.add(marker);
          map.setFitView(marker);
        }
      });
    });
  };

  const onPoint = () => {
    if (!value.name) return;
    const geoCoder = new AMap.Geocoder({
      city: '杭州',
    });
    geoCoder.getLocation(value.name, (status, result) => {
      if (status === 'complete' && result.geocodes.length) {
        const lnglat = result.geocodes[0].location;
        onChange({
          ...value,
          longitude: lnglat.lng,
          latitude: lnglat.lat,
        });
        marker.setPosition(lnglat);
        map.add(marker);
        map.setFitView(marker);
      } else {
        message.error('根据地址查询位置失败');
      }
    });
  };

  const handleChange = e => {
    onChange({
      ...value,
      name: e.target.value,
    });
  };

  useEffect(() => {
    onload();
  }, []);

  return (
    <div id="amap" className="amap">
      <Row>
        <Col span={20}>
          <Input
            className="mapInput"
            value={value.name}
            onChange={handleChange}
            type="text"
            placeholder="请输入地址"
          />
        </Col>
        <Col span={4}>
          <Button className="mapbtn" onClick={onPoint} type="primary">
            确定
          </Button>
        </Col>
      </Row>
    </div>
  );
};

export default Map;
